
package com.yuke.cloud.service.uac.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.yuke.cloud.common.base.dto.CheckValidDto;
import com.yuke.cloud.common.core.annotation.OperationLogDto;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.uac.constant.AccValidConstant;
import com.yuke.cloud.service.uac.dto.CheckLoginNameDto;
import com.yuke.cloud.service.uac.dto.ResetLoginPwdDto;
import com.yuke.cloud.service.uac.dto.UserModifyPwdByPhoneDto;
import com.yuke.cloud.service.uac.dto.UserRegisterDto;
import com.yuke.cloud.service.uac.entity.AccGroup;
import com.yuke.cloud.service.uac.entity.AccUser;
import com.yuke.cloud.service.uac.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 不认证的URL请求.
 *
 * @author
 */
@RestController
@RequestMapping(value = "/auth")
@Api(value = "Web-AuthRestController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AuthRestController extends BaseController {
	@Resource
	private AccUserService accUserService;
	@Resource
	private SmsService smsService;
	@Resource
	private EmailService emailService;
	@Resource
	private AccLogService accLogService;
	@Resource
	private AccRoleMenuService accRoleMenuService;
	@Resource
	private AccGroupService accGroupService;
	@Resource
	private AccUserController accUserController;

	/**
	 * 校验手机号码.
	 *
	 * @param mobileNo the mobile no
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkPhoneActive/{mobileNo}")
	@ApiOperation(httpMethod = "POST", value = "校验手机号码")
	public Wrapper<Boolean> checkPhoneActive(@PathVariable String mobileNo) {
		AccUser accUser = new AccUser();
//		accUser.setStatus(AccUserStatusEnum.ENABLE.getValue());
		accUser.setIsEnable(true);
		accUser.setMobile(mobileNo);
		int count = accUserService.selectCount(accUser);
		return WrapMapper.ok(count > 0);
	}

	/**
	 * 校验邮箱.
	 *
	 * @param email the email
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkEmailActive/{email:.+}")
	@ApiOperation(httpMethod = "POST", value = "校验邮箱")
	public Wrapper<Boolean> checkEmailActive(@PathVariable("email") String email) {
		AccUser accUser = new AccUser();
//		accUser.setStatus(AccUserStatusEnum.ENABLE.getValue());
		accUser.setIsEnable(true);
		accUser.setEmail(email);
		int count = accUserService.selectCount(accUser);
		return WrapMapper.ok(count > 0);
	}

	/**
	 * 校验数据.
	 *
	 * @param checkValidDto the check valid dto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkValid")
	@ApiOperation(httpMethod = "POST", value = "校验数据")
	public Wrapper checkValid(@RequestBody CheckValidDto checkValidDto) {
		String type = checkValidDto.getType();
		String validValue = checkValidDto.getValidValue();

		Preconditions.checkArgument(StringUtils.isNotEmpty(validValue), "参数错误");
		String message = null;
		boolean result = false;
		//开始校验
		if (AccValidConstant.Valid.LOGIN_NAME.equals(type)) {
			result = accUserService.checkLoginName(validValue);
			if (!result) {
				message = "用户名已存在";
			}
		}
		if (AccValidConstant.Valid.EMAIL.equals(type)) {
			result = accUserService.checkEmail(validValue);
			if (!result) {
				message = "邮箱已存在";
			}
		}

		if (AccValidConstant.Valid.MOBILE_NO.equals(type)) {
			result = accUserService.checkMobileNo(validValue);
			if (!result) {
				message = "手机号码已存在";
			}
		}

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, message, result);
	}


	/**
	 * 重置密码-邮箱-提交.
	 *
	 * @param email the email
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/submitResetPwdEmail")
	@ApiOperation(httpMethod = "POST", value = "重置密码-邮箱-提交")
	public Wrapper<String> submitResetPwdEmail(@RequestParam("email") String email) {
		logger.info("重置密码-邮箱-提交, email={}", email);
		emailService.submitResetPwdEmail(email);
		return WrapMapper.ok();
	}


	/**
	 * 重置密码-手机-提交.
	 *
	 * @param mobile   the mobile
	 * @param response the response
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/submitResetPwdPhone")
	@ApiOperation(httpMethod = "POST", value = "重置密码-手机-提交")
	public Wrapper<String> submitResetPwdPhone(@RequestParam("mobile") String mobile, HttpServletResponse response) {
		logger.info("重置密码-手机-提交, mobile={}", mobile);
		String token = smsService.submitResetPwdPhone(mobile, response);
		return WrapMapper.ok(token);
	}

	/**
	 * 重置密码-最终提交.
	 *
	 * @param resetLoginPwdDto the reset login pwd dto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/resetLoginPwd")
	@ApiOperation(httpMethod = "POST", value = "重置密码-最终提交")
	public Wrapper<Boolean> checkResetSmsCode(ResetLoginPwdDto resetLoginPwdDto) {
		accUserService.resetLoginPwd(resetLoginPwdDto);
		return WrapMapper.ok();
	}

	/**
	 * 注册用户.
	 *
	 * @param user the user
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/register")
	@ApiOperation(httpMethod = "POST", value = "注册用户", notes = "消息体中通过Json将注册信息传递")
	public Wrapper registerUser(@RequestBody UserRegisterDto user) {
		if (user.getEmployeeType() != null && user.getGroupId() != null){
			accUserService.registerEmployee(user);
		}else{
			accUserService.register(user);
		}

		//todo 注册完成后可与社交用户绑定
		//将业务系统的用户与社交用户绑定，登录名代替用户名
		//AppSingUpUtils.doPostSignUp(new ServletWebRequest(request), user.getLoginName());
		return WrapMapper.ok();
	}

	/**
	 * 注册用户+店铺注册.
	 *
	 * @param jsonObject the phoneNumber
	 *
	 *
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/registerUserAndShop")
	@ApiOperation(httpMethod = "POST", value = "注册用户和店铺", notes = "请求头中将注册信息传递")
	public Wrapper autoRegisterUserAndShop(@RequestBody JSONObject jsonObject) {

		String phoneNumber = jsonObject.get("phoneNumber").toString();
		String shopName = jsonObject.get("shopName").toString();
		Long wareHouseId = Long.parseLong(jsonObject.get("wareHouseId").toString());
		String address = jsonObject.get("address").toString();

		CheckLoginNameDto checkLoginNameDto = new CheckLoginNameDto();
		checkLoginNameDto.setLoginName(shopName);
		Wrapper<Boolean> wrap = accUserController.checkLoginName(checkLoginNameDto);
		if (!wrap.getResult()){
			return  WrapMapper.error("店铺名称有重复的，请更换其他名称。");
		}
		//填充用户信息
		UserRegisterDto userRegisterDto = new UserRegisterDto();
		userRegisterDto.setMobileNo(phoneNumber);
		userRegisterDto.setLoginPwd("123456");
		userRegisterDto.setConfirmPwd("123456");
		userRegisterDto.setRegisterSource("0");
		userRegisterDto.setAddress(address);

		Integer num = accUserService.autoRegisterUserAndShop(userRegisterDto, shopName, wareHouseId);

		return WrapMapper.ok(num);
	}



	/**
	 * 激活用户.
	 *
	 * @param activeUserToken the active user token
	 *
	 * @return the wrapper
	 */
	@GetMapping(value = "/activeUser/{activeUserToken}")
	@ApiOperation(httpMethod = "POST", value = "激活用户")
	public Wrapper activeUser(@PathVariable String activeUserToken) {
		accUserService.activeUser(activeUserToken);
		return WrapMapper.ok("激活成功");
	}

	/**
	 * 查询日志.
	 *
	 * @param operationLogDto the operation log dto
	 *
	 * @return the integer
	 */
	@PostMapping(value = "/saveLog")
	@ApiOperation(httpMethod = "POST", value = "查询日志")
	public Integer saveLog(@RequestBody OperationLogDto operationLogDto) {
		logger.info("saveLog - 保存操作日志. operationLogDto={}", operationLogDto);
		return accLogService.saveOperationLog(operationLogDto);
	}

	@PostMapping(value = "/callback/qq")
	public void callbackQQ(HttpServletRequest request) {
		logger.info("callback - callback qq. request={}", request);
	}

	/**
	 * 根据用户ID获取用户的菜单URL列表.
	 *
	 * @param id the operation log dto
	 *
	 * @return the integer
	 */
	@GetMapping(value = "/ownMenuUrl/{id}")
	@ApiOperation(httpMethod = "GET", value = "根据用户ID获取用户的菜单URL列表")
	public Wrapper<List<String>> getOwnMenuUrlList(@ApiParam(name = "id", value = "用户id") @PathVariable Long id) {
		List<String> list = accRoleMenuService.getOwnMenuUrlList(id);

		return WrapMapper.ok(list);
	}

	/**
	 * 重设密码-手机-提交.
	 *
	 * @param userModifyPwdByPhoneDto   the UserModifyPwdByPhoneDto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/resetPwdPhone")
	@ApiOperation(httpMethod = "POST", value = "重置密码-手机-提交")
	public Wrapper<String> getBackPwdPhone(@RequestBody UserModifyPwdByPhoneDto userModifyPwdByPhoneDto) {
		int result = accUserService.userModifyPwdByPhone(userModifyPwdByPhoneDto);

		if (result > 0) {
			return WrapMapper.ok();
		}
		return WrapMapper.error();
	}

	@GetMapping(value = "/getGroupList")
	@ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
	public Wrapper<List<AccGroup>> list() {
		Example example = new Example(AccGroup.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("level",2);
		criteria.andEqualTo("parentId",1);
		List<AccGroup> list = accGroupService.selectByExample(example);

		return WrapMapper.ok(list);
	}
}
